"use client";

import { gqlError } from "@/libs/apollo-errors";
import { setCookie } from "@/libs/cookie";
import { gql, useMutation } from "@apollo/client";
import { Button, Form, Input } from "antd";
import { useCallback, useEffect } from "react";
import AuthLayout from "./AuthLayout";
import useViewer from "@/hooks/auth/useViewer";
import { useRouter } from "next/navigation";

const AuthMutation = gql`
  mutation Auth($account: String!, $password: String!) {
    auth(account: $account, password: $password) {
      token
      role
    }
  }
`;

const HomePage = () => {
  const user = useViewer();
  const router = useRouter();
  useEffect(() => {
    if (!user) return;
    if (user.role > 100) {
      router.push("/admin");
    } else {
      router.push("/user");
    }
  }, [user]);
  const [auth, { loading }] = useMutation(AuthMutation, {
    onCompleted({ auth: { token, role } }) {
      setCookie("token", token);
      if (role > 100) {
        router.push("/admin");
      } else {
        router.push("/user");
      }
    },
    onError(error) {
      gqlError(error);
    },
  });

  const onFinish = useCallback((variables: any) => {
    auth({
      variables,
    });
  }, []);

  return (
    <AuthLayout>
      <div className="flex items-center justify-center min-h-screen bg-gray-100 p-2">
        <div className="w-full max-w-md p-8 space-y-6 bg-white rounded-lg shadow-md">
          <h2 className="text-3xl font-bold text-center text-gray-800">登录</h2>
          <Form onFinish={onFinish} layout="vertical">
            <Form.Item
              required
              name="account"
              label="账号"
              rules={[{ required: true, message: "请输入您的账号" }]}
            >
              <Input placeholder="请输入账号" />
            </Form.Item>
            <Form.Item
              required
              name="password"
              label="密码"
              rules={[{ required: true, message: "请输入您的密码" }]}
            >
              <Input.Password placeholder="请输入密码" />
            </Form.Item>
            <Form.Item>
              <Button
                loading={loading}
                block
                htmlType="submit"
                className="bg-blue-500 hover:bg-blue-600 text-white font-semibold"
              >
                登录
              </Button>
            </Form.Item>
          </Form>
          <div className="text-center"></div>
        </div>
      </div>
    </AuthLayout>
  );
};

export default HomePage;
